import axios from 'axios'
// import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

import {refresh} from '../api/user'
let expiredList = [] //存储过期的请求

// 把过期请求添加在数组中
function addRequest(request) {
    expiredList.push(request)
}

// create an axios instance
const service = axios.create({
    baseURL: window.CONFIG.baseURL, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        const token = sessionStorage.getItem('token')
        expiredList.push(config)
        if (token) {
            // let each request carry token
            // ['X-Token'] is a custom headers key
            // please modify it according to the actual situation
            config.headers['token'] = token
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data
       if (res.code === 403) {
            // 把过期请求存储起来，用于请求到新的刷新token
           refresh({refreshToken: sessionStorage.getItem('refreshToken')}).then(n => {
               console.log('expiredList', expiredList)
           })

        } else if (res.code !== 20000) {
           return Promise.reject(new Error(res.message || 'Error'))
       } else {
            return res.result
        }
    },
    error => {
        console.log('err' +  error) // for debug
        return Promise.reject(error)
    }
)

export default service
